package com.wang.tasker.plug.net.ftp;

import java.io.PrintWriter;
import java.util.List;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wang.tasker.core.ConfigElement;
import com.wang.tasker.core.TaskPackage;
import com.wang.tasker.plug.net.Connection;

public class FTPConnection implements Connection {

	private FTPClient client;
	
	private String server;
	
	private int port = 21;
	
	private String user;
	
	private String password;
	
	private FTPTask task;
	
	private static Logger logger = LoggerFactory.getLogger(FTPConnection.class);
	
	public FTPConnection(FTPTask task){
		this.task = task;
	}

	public void init(ConfigElement confEle) {
		ConfigElement connEle = confEle.selectSingleElement("Connection");
		if(connEle == null)//TODO add task name to exception infomation. based on TaskContext Object
			throw new RuntimeException("FTPConnection miss <Connection> Element...");
		
		List subEles = connEle.elements();
		for(Object objEle:subEles){
			ConfigElement ele = (ConfigElement)objEle;
			String eleName = ele.getName();
			if("Server".equals(eleName)){
				this.server = ele.getTextTrim();
			} else if("Port".equals(eleName)){
				this.port = Integer.parseInt(ele.getTextTrim());
			} else if("User".equals(eleName)){
				this.user = ele.getTextTrim();
			} else if("Password".equals(eleName)){
				this.password = ele.getTextTrim();
			}
		}
	}
	
	private void initClient() throws Exception{
		logger.debug("Connection FTP: {}@{}:{}",new String[]{this.user, this.server, this.port+""});
		client = new FTPClient();
		client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        int reply;
		client.setDefaultPort(this.port);
		client.connect(this.server);
        reply = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
        	client.disconnect();
            throw new Exception("Exception in connecting to FTP Server");
        }
		client.setDataTimeout(120000); 
		client.login(this.user, this.password);
	}

	public FTPClient getClient() throws Exception {
		if(client == null)
			initClient();
		return client;
	}

	public String getServer() {
		return server;
	}

	public int getPort() {
		return port;
	}

	public String getUser() {
		return user;
	}

	public String getPassword() {
		return password;
	}
	
	
	
}
